CODE 48. Maximal Rectangle

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public int maximalRectangle(char[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == matrix || matrix.length <= 0) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] vmax = new int[rows][cols];
if (matrix[0][0] == '1') {
vmax[0][0] = 1;
}
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i == 0) {
if (matrix[i][j] == '1') {
vmax[i][j] = 1;
}
} else {
if (matrix[i][j] == '1') {
vmax[i][j] = 1 + vmax[i - 1][j];
} else {
vmax[i][j] = 0;
}
}
}
}
for (int i = rows - 1; i >= 0; i--) {
int tmp = largestRectangleArea(vmax[i]);
if (tmp > maximum) {
maximum = tmp;
}
}
return maximum;
}
Jerky Lu wechat
欢迎加入微信公众号